﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Threading;

public partial class TrackingManage_AlertList : BasePage
{
    ISendTruckHandler stManager = new SendTruckHandler();
    DataBase db = new DataBase();
    private static bool isView = false;
    string language = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        language = Thread.CurrentThread.CurrentUICulture.ToString().ToLower();
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!strPermission.Contains("1069"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    if (strPermission.Contains("1066"))
                    {
                        isView = true;
                    }
                    else
                    {
                        isView = false;
                    }
                }


            }

            ViewState["OrderBy"] = "LastModDate";
            ViewState["Accending"] = "desc";
            dataBind();
            initSearchBox();
        }
    }

    private void initSearchBox()
    {
        fillShipper();
        fillWhouse();
        fillVendor();
    }

    private void fillShipper()
    {
        ISyClientHandler clientManager = new SyClientHandler();
        DataTable dt = clientManager.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        lstShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstShipper.DataTextField = "HKShortName";
        }
        else
        {
            lstShipper.DataTextField = "CNShortName";
        }
        lstShipper.DataValueField = "PKID";
        lstShipper.DataBind();
    }

    private void fillWhouse()
    {
        ISyClientHandler clientManager = new SyClientHandler();
        string sqlStr = "SELECT DISTINCT client.* FROM Sy_Client client " +
                        " inner join Sy_ClientType type on client.PKID = type.ClientID " +
                        " inner join Sy_Code code on type.SyCodeID = code.PKID" +
                        " where code.Type='CT' and (code.Code = 'MT' or code.Code = 'CK') AND client.Status = 1";
        DataTable dt = clientManager.GetClientList(sqlStr, null);
        ddlWhouse.DataSource = dt;
        ddlWhouse.DataTextField = ("en".Equals(language) ? "ENGShortName" : ("zh-hk".Equals(language) ? "HKShortName" : "CNShortName"));
        ddlWhouse.DataValueField = "PKID";
        ddlWhouse.DataBind();
        ddlWhouse.Items.Insert(0, new ListItem("select...", "0"));
    }

    private void fillVendor()
    {
        ISyClientHandler clientManager = new SyClientHandler();
        string sqlStr = @"SELECT DISTINCT client.* FROM Sy_Client client 
                         inner join Sy_ClientType type on client.PKID = type.ClientID
                         inner join Sy_Code code on type.SyCodeID = code.PKID
                         where code.Type='CT' and code.Code = 'GQ' AND client.Status = 1";

        DataTable dt = clientManager.GetClientList(sqlStr, null);
        ddlVendor.DataSource = dt;
        ddlVendor.DataTextField = ("en".Equals(language) ? "ENGShortName" : ("zh-hk".Equals(language) ? "HKShortName" : "CNShortName"));
        ddlVendor.DataValueField = "PKID";
        ddlVendor.DataBind();
        ddlVendor.Items.Insert(0, new ListItem("select...", "0"));
    }


    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        
        if (ViewState["Shipper"] != null)
        {
            sqlstr += " and (shipper.PKID in (" + ViewState["Shipper"] + ")) ";
        }
        if (ViewState["Whouse"] != null)
        {
            list.Add(new SqlParameter("@Whouse", ViewState["Whouse"].ToString()));
            sqlstr += " and whouse.PKID = @Whouse";
        }
        if (ViewState["Vendor"] != null)
        {
            list.Add(new SqlParameter("@Vendor", ViewState["Vendor"].ToString()));
            sqlstr += " and vendor.PKID = @Vendor";
        }
        if (ViewState["JobDate"] != null)
        {
            list.Add(new SqlParameter("@JobDate", ViewState["JobDate"].ToString()));
            sqlstr += " and JobDate = @JobDate";
        }

        // 如果当前登录用户有所属公司，则只查出该公司
        if (Session["LoginUserClientID"].ToString() != "0")
        {
            sqlstr = sqlstr + " and st.Contractor =" + Session["LoginUserClientID"].ToString();
        }
        parms = list.ToArray();
    }

    private void dataBind()
    {
        string sqlStr = @"SELECT DISTINCT vendor.CNShortName as Vendor, vendor.HKShortName as HKVendor, vendor.ENGShortName as ENGVendor,
                            vendor.PKID as VendorID,cm.Model as Type, truck.LicenseNO, driver.Name as Driver,
                            p.Place, p.HKPlace, p.ENGPlace,w.Whouse,w.HKWhouse,w.ENGWhouse,Shipper, HKShipper, ENGShipper,
                            contractor.CNShortName as Contractor, contractor.HKShortName as HKContractor, contractor.ENGShortName as ENGContractor,
                            contractor.PKID as ContractorID,st.LastModDate, truck.PKID as TruckID, st.PKID as STID,
                            (SELECT [values] FROM(
                                SELECT DISTINCT OrderID FROM BN_ShippingOrderDtl WHERE OrderID = so.PKID
                            )A OUTER APPLY(
                                    SELECT [values] = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT CONVERT(varchar(19) , JobDate, 121) as JobDate FROM BN_ShippingOrderDtl N WHERE OrderID = A.OrderID FOR XML AUTO
                                    ), '<N JobDate=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, '')
                            )N) as JobDate,
                            (SELECT [values] FROM (
                                SELECT DISTINCT OrderID FROM BN_ShippingOrderDtl WHERE OrderID = so.PKID
                            )A OUTER APPLY (
                                SELECT [values] = STUFF(REPLACE(REPLACE((
                                    SELECT DISTINCT SONO FROM BN_ShippingOrderDtl N WHERE OrderID = A.OrderID FOR XML AUTO
                                ), '<N SONO=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, '')
                            )N)as SONO,
                            (
                                SELECT [values] FROM (
                                    SELECT DISTINCT OrderID FROM BN_ShippingOrderDtl WHERE OrderID = so.PKID
                                )A OUTER APPLY (
                                    SELECT [values] = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT CAST(VOL AS VARCHAR) AS VOL FROM BN_ShippingOrderDtl N WHERE OrderID = A.OrderID FOR XML AUTO
                                    ), '<N VOL=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, '')
                                )N
                            )as VOL,truckstatus.StatusName as LastTracking, truckstatus.HKStatusName as HKLastTracking,
                            truckstatus.ENGStatusName as ENGLastTracking, tracking.CEDate as LastTrackingEndDate
                        FROM BN_SendTruck st LEFT JOIN
                            BN_ShippingOrder so ON st.OrderID = so.PKID LEFT JOIN
                            BN_ShippingOrderDtl soDtl ON so.PKID = soDtl.OrderID LEFT JOIN
                            BN_SendTruckDtl stDtl ON st.PKID = stDtl.SendTruckID LEFT JOIN
                            BN_Truck truck ON stDtl.TruckID = truck.PKID LEFT JOIN
                            BN_Driver driver ON stDtl.Driver = driver.PKID LEFT JOIN
                            Sy_Client shipper ON soDtl.ShipperID = shipper.PKID LEFT JOIN
                            Sy_Client vendor ON so.VendorID = vendor.PKID LEFT JOIN
                            Sy_Client whouse ON soDtl.WhouseID = whouse.PKID LEFT JOIN
                            Sy_Client contractor ON st.Contractor = contractor.PKID LEFT JOIN
                            Sy_ContainerModel cm ON stDtl.TypeID = cm.PKID INNER JOIN
                            (
                                SELECT * FROM BN_TTracking WHERE PKID IN (
                                    SELECT MAX(PKID) FROM BN_TTracking GROUP BY TruckID, SendTruckID
                                ) AND CEDate < GETDATE()
                            ) tracking ON truck.PKID = tracking.TruckID AND
                                    st.PKID = tracking.SendTruckID INNER JOIN
                            Sy_TruckStatus truckstatus ON tracking.TruckStatusID = truckstatus.PKID

                        OUTER APPLY
                            (
                                SELECT Shipper, HKShipper, ENGShipper FROM (
                                    SELECT DISTINCT OrderID FROM BN_ShippingOrderDtl WHERE OrderID = so.PKID
                                )A OUTER APPLY (
                                    SELECT Shipper = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT shipper.CNShortName FROM BN_ShippingOrderDtl soDtl INNER JOIN
                                            Sy_Client shipper ON soDtl.ShipperID = shipper.PKID
                                        WHERE soDtl.OrderID = A.OrderID
                                        FOR XML AUTO
                                    ), '<shipper CNShortName=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, ''),
                                    HKShipper = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT shipper.HKShortName FROM BN_ShippingOrderDtl soDtl INNER JOIN
                                            Sy_Client shipper ON soDtl.ShipperID = shipper.PKID
                                        WHERE soDtl.OrderID = A.OrderID
                                        FOR XML AUTO
                                    ), '<shipper HKShortName=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, ''),
                                    ENGShipper = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT shipper.ENGShortName FROM BN_ShippingOrderDtl soDtl INNER JOIN
                                            Sy_Client shipper ON soDtl.ShipperID = shipper.PKID
                                        WHERE soDtl.OrderID = A.OrderID
                                        FOR XML AUTO
                                    ), '<shipper ENGShortName=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, '')
                                )N
                            ) s
                        OUTER APPLY
                            (
                                SELECT Place, HKPlace, ENGPlace FROM (
                                    SELECT DISTINCT OrderID FROM BN_ShippingOrderDtl WHERE OrderID = so.PKID
                                )A OUTER APPLY (
                                    SELECT Place = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT place.Name FROM Sy_Client vv INNER JOIN
                                            Sy_Place place ON vv.PlaceID = place.PKID
                                        WHERE vv.PKID = vendor.PKID
                                        FOR XML AUTO
                                    ), '<place Name=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, ''),
                                    HKPlace = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT place.HKName FROM Sy_Client vv INNER JOIN
                                            Sy_Place place ON vv.PlaceID = place.PKID
                                        WHERE vv.PKID = vendor.PKID
                                        FOR XML AUTO
                                    ), '<place HKName=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, ''),
                                    ENGPlace = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT place.ENGName FROM Sy_Client vv INNER JOIN
                                            Sy_Place place ON vv.PlaceID = place.PKID
                                        WHERE vv.PKID = vendor.PKID
                                        FOR XML AUTO
                                    ), '<place ENGName=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, '')
                                )N
                            )as p
                        OUTER APPLY
                            (
                                SELECT Whouse,HKWhouse,ENGWhouse FROM (
                                    SELECT DISTINCT OrderID FROM BN_ShippingOrderDtl WHERE OrderID = so.PKID
                                )A OUTER APPLY (
                                    SELECT Whouse = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT whouse.CNShortName FROM BN_ShippingOrderDtl soDtl INNER JOIN
                                            Sy_Client whouse ON soDtl.WhouseID = whouse.PKID
                                        WHERE soDtl.OrderID = A.OrderID
                                        FOR XML AUTO
                                    ), '<whouse CNShortName=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, ''),
                                    HKWhouse = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT whouse.HKShortName FROM BN_ShippingOrderDtl soDtl INNER JOIN
                                            Sy_Client whouse ON soDtl.WhouseID = whouse.PKID
                                        WHERE soDtl.OrderID = A.OrderID
                                        FOR XML AUTO
                                    ), '<whouse HKShortName=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, ''),
                                    ENGWhouse = STUFF(REPLACE(REPLACE((
                                        SELECT DISTINCT whouse.ENGShortName FROM BN_ShippingOrderDtl soDtl INNER JOIN
                                            Sy_Client whouse ON soDtl.WhouseID = whouse.PKID
                                        WHERE soDtl.OrderID = A.OrderID
                                        FOR XML AUTO
                                    ), '<whouse ENGShortName=" + "\"" + "', ', '), '" + "\"" + @"/>', ''), 1, 1, '')
                                )N
                            ) w
                        WHERE (so.Status = " + HK2009.Common.Enums.ShippingOrderStatus.CHECK.ToString("d") + 
                       " or so.Status = " + HK2009.Common.Enums.ShippingOrderStatus.CONFIM.ToString("d") +
                       " or so.Status = " + HK2009.Common.Enums.ShippingOrderStatus.PRINT.ToString("d") + ")";
        SqlParameter[] parms = null;
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        DataTable dt = stManager.GetList(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvAlertList.DataSource = view;
        gvAlertList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    //protected void GoPage_TextChanged(object sender, EventArgs e)
    //{
    //    int i = Convert.ToInt32(((DropDownList)sender).Text) - 1;
    //    if (i >= 0 && i < gvMarketList.PageCount)
    //    {
    //        this.gvMarketList.PageIndex = i;
    //        //数据绑定
    //        dataBind();
    //    }
    //}

    //public int[] CreatSource(int numFrom, int numTo)
    //{
    //    int num = numTo - numFrom + 1;
    //    int[] a = new int[num];
    //    for (int i = 0; i < num; i++) { a[i] = i + numFrom; }
    //    return a;
    //}

    protected void gvAlertList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvAlertList.PageIndex = e.NewPageIndex;
        dataBind();

    }
    protected void gvAlertList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dataBind();

    }
    protected void gvAlertList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            string item = string.Empty;
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                item += lstSelShipper.Items[i].Value + ",";
            }
            ViewState["Shipper"] = item.Substring(0, item.Length - 1);
        }
        else
        {
            ViewState["Shipper"] = null;
        }
        if (ddlWhouse.SelectedValue != "0")
        {
            ViewState["Whouse"] = ddlWhouse.SelectedValue;
        }
        else
        {
            ViewState["Whouse"] = null;
        }
        if (ddlVendor.SelectedValue != "0")
        {
            ViewState["Vendor"] = ddlVendor.SelectedValue;
        }
        else
        {
            ViewState["Vendor"] = null;
        }
        if (txtJobDate.Text != null && txtJobDate.Text.Trim() != "")
        {
            try
            {
                DateTime.Parse(txtJobDate.Text.Trim());
                ViewState["JobDate"] = txtJobDate.Text.Trim();
            }
            catch { ViewState["JobDate"] = null; }
        }
        else
        {
            ViewState["JobDate"] = null;
        }
        
        dataBind();
    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvAlertList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }
    protected void gvAlertList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblView = (Label)e.Row.FindControl("lblView");

            lblView.Visible = isView;


            Label lblLastTracking = (Label)e.Row.FindControl("lblLastTracking");
            Label lblHKLastTracking = (Label)e.Row.FindControl("lblHKLastTracking");
            Label lblENGLastTracking = (Label)e.Row.FindControl("lblENGLastTracking");

            Label lblShipper = (Label)e.Row.FindControl("lblShipper");
            Label lblHKShipper = (Label)e.Row.FindControl("lblHKShipper");
            Label lblENGShipper = (Label)e.Row.FindControl("lblENGShipper");

            Label lblVendor = (Label)e.Row.FindControl("lblVendor");
            Label lblHKVendor = (Label)e.Row.FindControl("lblHKVendor");
            Label lblENGVendor = (Label)e.Row.FindControl("lblENGVendor");

            Label lblPlace = (Label)e.Row.FindControl("lblPlace");
            Label lblHKPlace = (Label)e.Row.FindControl("lblHKPlace");
            Label lblENGPlace = (Label)e.Row.FindControl("lblENGPlace");

            Label lblWhouse = (Label)e.Row.FindControl("lblWhouse");
            Label lblHKWhouse = (Label)e.Row.FindControl("lblHKWhouse");
            Label lblENGWhouse = (Label)e.Row.FindControl("lblENGWhouse");

            Label lblContractor = (Label)e.Row.FindControl("lblContractor");
            Label lblHKContractor = (Label)e.Row.FindControl("lblHKContractor");
            Label lblENGContractor = (Label)e.Row.FindControl("lblENGContractor");

            if ("en".Equals(language))
            {
                lblLastTracking.Visible = false;
                lblHKLastTracking.Visible = false;
                lblENGLastTracking.Visible = true;

                lblShipper.Visible = false;
                lblHKShipper.Visible = false;
                lblENGShipper.Visible = true;

                lblVendor.Visible = false;
                lblHKVendor.Visible = false;
                lblENGVendor.Visible = true;

                lblPlace.Visible = false;
                lblHKPlace.Visible = false;
                lblENGPlace.Visible = true;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = true;

                lblContractor.Visible = false;
                lblHKContractor.Visible = false;
                lblENGContractor.Visible = true;
            }
            else if ("zh-hk".Equals(language))
            {
                lblLastTracking.Visible = false;
                lblHKLastTracking.Visible = true;
                lblENGLastTracking.Visible = false;

                lblShipper.Visible = false;
                lblHKShipper.Visible = true;
                lblENGShipper.Visible = false;

                lblVendor.Visible = false;
                lblHKVendor.Visible = true;
                lblENGVendor.Visible = false;

                lblPlace.Visible = false;
                lblHKPlace.Visible = true;
                lblENGPlace.Visible = false;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = true;
                lblENGWhouse.Visible = false;

                lblContractor.Visible = false;
                lblHKContractor.Visible = true;
                lblENGContractor.Visible = false;
            }
            else
            {
                lblLastTracking.Visible = true;
                lblHKLastTracking.Visible = false;
                lblENGLastTracking.Visible = false;

                lblShipper.Visible = true;
                lblHKShipper.Visible = false;
                lblENGShipper.Visible = false;

                lblVendor.Visible = true;
                lblHKVendor.Visible = false;
                lblENGVendor.Visible = false;

                lblPlace.Visible = true;
                lblHKPlace.Visible = false;
                lblENGPlace.Visible = false;

                lblWhouse.Visible = true;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = false;

                lblContractor.Visible = true;
                lblHKContractor.Visible = false;
                lblENGContractor.Visible = false;
            }
        }
    }


    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvAlertList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvAlertList.PageCount)
            {
                this.gvAlertList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }

    protected void btnAddSShipper_Click(object sender, EventArgs e)
    {
        if (lstShipper.SelectedValue != string.Empty)
        {
            for (int i = 0; i < lstShipper.Items.Count; i++)
            {
                bool issel = false;
                if (lstShipper.Items[i].Selected)
                {
                    for (int j = 0; j < lstSelShipper.Items.Count; j++)
                    {
                        if (lstShipper.Items[i].Value == lstSelShipper.Items[j].Value)
                        {
                            issel = true;
                            break;
                        }
                    }

                    if (!issel)
                    {
                        ListItem item = new ListItem();
                        item.Text = lstShipper.Items[i].Text;
                        item.Value = lstShipper.Items[i].Value;
                        lstSelShipper.Items.Add(item);
                    }
                }
            }
        }
        else
        {

        }

    }
    protected void btnDeleteSShipper_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            ListItemCollection lstColl = new ListItemCollection();
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                if (!lstSelShipper.Items[i].Selected)
                {
                    ListItem item = new ListItem(lstSelShipper.Items[i].Text, lstSelShipper.Items[i].Value);
                    lstColl.Add(item);
                }
            }
            if (lstColl != null && lstColl.Count > 0)
            {
                lstSelShipper.Items.Clear();
                for (int j = 0; j < lstColl.Count; j++)
                {
                    lstSelShipper.Items.Add(lstColl[j]);
                }
            }
            else
            {
                lstSelShipper.Items.Clear();
            }

        }
    }
}
